<template>
    <div class="container-column">
        <el-card shadow="never" class="card-com">
            <div class="card-1">
                <searchPanel @refresh="getData('reset')">
                    <!-- 查询面板 -->
                    <template v-slot:search>
                        <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
                            <el-row :gutter="20">
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="渠道Key">
                                        <el-input v-model="listSearch.condition.channelKey" clearable
                                            placeholder="请输入渠道Key" @keyup.enter.native="getData('search')"
                                            @clear="getData('search')" />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="渠道编码">
                                        <el-input v-model="listSearch.condition.channelCode" clearable
                                            placeholder="请输入渠道编码" @keyup.enter.native="getData('search')"
                                            @clear="getData('search')" />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="渠道名称">
                                        <el-input v-model="listSearch.condition.channelName" clearable
                                            placeholder="请输入渠道名称" @keyup.enter.native="getData('search')"
                                            @clear="getData('search')" />
                                    </el-form-item>
                                </el-col>


                            </el-row>
                            <el-row justify="end">
                                <el-button type="primary" @click="getData('search')">查询</el-button>
                                <el-button @click="getData('reset')">重置</el-button>
                            </el-row>
                        </el-form>
                    </template>
                    <!-- 字段添加 -->
                    <template v-slot:edit>
                        <el-button :icon="Refresh" type="primary" @click="refreshChannel" title="刷新渠道信息"></el-button>
                        <el-button :icon="Plus" v-permission="'CHANNEL:CREATE-EDIT'" type="primary"
                            @click="AddEdit('add')" title="新增渠道信息"></el-button>
                        <el-button :icon="Download" v-permission="'CHANNEL:EXPORT'" title="下载渠道列表"
                            @click="btnDown"></el-button>
                        <el-button :icon="List" v-permission="'CHANNEL:EXPORT'" title="查看下载渠道列表"
                            @click="btnDownList"></el-button>
                        <DropItem v-model:table-prop="tableProp"></DropItem>
                    </template>
                </searchPanel>
            </div>
            <div class="card-2">

                <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total"
                    @get-page="handPage" :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight"
                    :loading="pageParams.loadIng">
                    <template #quickCopy="scope">
                        <el-button size="small" type="primary" @click="handleCopy(scope.row, $event)">一键复制</el-button>
                    </template>
                    <template #handle="scope">


                        <el-button type="primary" size="small" link @click="AddEdit('edit', scope.row)"
                            v-permission="'CHANNEL:CREATE-EDIT'">编辑</el-button>
                        <el-button type="primary" size="small" link @click="addPerProduct(scope.row)"
                            v-permission="'CHANNEL:CREATE-EDIT'">关联产品</el-button>
                        <el-button type="primary" size="small" link @click="addInfo(scope.row)"
                            v-permission="'CHANNEL:DETAIL'">附加信息</el-button>
                        <el-button type="danger" @click="delBtn(scope.row)" v-permission="'CHANNEL:DELETE'" link
                            size="small">删除</el-button>
                        <el-button type="primary" size="small" link @click="detailBtn(scope.row)"
                            v-permission="'CHANNEL:DETAIL'">详情</el-button>
                    </template>
                </OnlyTable>
            </div>
        </el-card>

        <addEditVue ref="channelAddEditRef" :channelList="listCollect.merchantList" @searchEdit="getData('search')"
            @refresh="getData('reset')">
        </addEditVue>
        <addProduct ref="addProductRef" @refresh="getData('search')"></addProduct>

        <downList ref="downListRef" @flash="btnDownList"></downList>
        <Information ref="informationRef"></Information>
        <FormDetail :detailData="detailData" ref="detailRef"></FormDetail>
    </div>

</template>

<script setup lang='ts'>
/*******************************************外部引入************************************************* */
import { reactive, onMounted, defineAsyncComponent, ref, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus"
import { storeToRefs } from "pinia";
import _ from "lodash"
import dayjs from "dayjs"

import { Download, Plus, List,Refresh } from '@element-plus/icons-vue'
import useInstance from '@/hooks/useInstance';
import { channelPageApiPost, channelDeleteApiDelete, channelDetailApiGet, channelRelationProductListApiPost, additionalListPost } from "@/api/userMangement"
import { oldSystemDataMigrationChannelPost } from "@/api/businessTraffic"
import { channelListStore } from "./pageStore"
import { exportExportChannelApiPost } from "@/api/fileDown"
import clip from '@/utils/clipboard'
import { useComListData } from "@/store/list"
import mittBus from '@/utils/mitt';
defineOptions({
    name: "channelList",
});

/*******************************************定义数据************************************************* */
const auditStatus: any = {
    "1": "初始化",
    "2": "审核通过",
    "3": "审核拒绝"
}
const { detailData, tableProp } = storeToRefs(channelListStore())
const { global } = useInstance();
const addEditVue = defineAsyncComponent(() => import("./components/addEdit.vue"))
const downList = defineAsyncComponent(() => import("@/components/downList.vue"))
const addProduct = defineAsyncComponent(() => import("./components/addProduct.vue"))
const Information = defineAsyncComponent(() => import("./components/Information.vue"))
const channelAddEditRef = ref<{ show: (type: string, row?: any) => void }>()
const downListRef = ref<{ show: (title: string, row?: any) => void }>()
const addProductRef = ref<{ show: (type: string, row?: any, list?: any) => void }>()
const informationRef = ref<{ show: (title: string, row?: any, data?: any) => void }>()
const detailRef = ref<{ show: (title: string, row?: any) => void }>()
const onlyTableRef = ref()
const listSearch = reactive({
    orders: ["id desc"],
    condition: {
        channelKey: null,
        channelCode: null,
        channelName: null
    },
    pageSize: 20,
    pageNum: 1
});
const pageParams = reactive({
    tableHeight: 400,
    total: 0,
    loadIng: false,
    tableData: [],
    channelList: [],
    productList: []
})

const { listCollect } = storeToRefs(useComListData())
/*******************************************定义方法************************************************* */
const { getEnvList, getSceneList, getSchemeList, getProListAll, getReportingPlatformCode, getMerchantList } = useComListData()
const handleCopy = (text: any, event: any) => {
    clip(`${text.channelName} - ${text.channelCode}`, event)
}
const addInfo = async (row: any) => {
    const res = await additionalListPost({ channelCode: row.channelCode })
    if (res.code == 20000) {
        console.log(res.data);

        informationRef.value?.show('add', row, res.data)
    }
}
const refreshChannel = async () => {

    let today: any = new Date();

    today = dayjs(today).format("YYYY-MM-DD HH:mm:ss")
    const res = await oldSystemDataMigrationChannelPost({
        "lastUpdateTime": today
    })
    if (res.code == 20000) {

        ElMessage({
            type: "success",
            message: '渠道同步数据成功'
        });
        getData('reset')

    } else {
        ElMessage({
            type: "error",
            message: res.message
        });
    }
}
const detailBtn = async (row: any) => {
    try {
        const res = await channelDetailApiGet({ id: row.id })
        if (res.code != 20000) return
        detailData.value = detailData.value.map(item => {
            if (item.prop == "auditStatus") {
                return {
                    ...item,
                    value: auditStatus[res.data[item.prop]]

                }
            } else if (item.prop == "channelMerchantCode") {
                return {
                    ...item,
                    value: res.data['channelMerchantCode'] + " - " + res.data['channelMerchantName']
                }
            } else {
                return {
                    ...item,
                    value: res.data[item.prop]
                }
            }
        })
        detailRef.value.dialogBasic.height = 400
        detailRef.value?.show('edit')
    } catch (error) {

    }
}
onMounted(() => {
    getData('search')

    getEnvList()
    getSceneList()
    getSchemeList()
    getProListAll({})
    getReportingPlatformCode()
    getMerchantList()
})


const addPerProduct = async (row: any) => {
    addProductRef.value?.show('add', row)
}

const btnDownList = async () => {
    // 发送请求 传递数据
    downListRef.value?.show('渠道下载列表', 'channel')
}

// 需要做一个 
const btnDown = async () => {
    try {
        const res = await exportExportChannelApiPost({ condition: listSearch.condition })
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "下载成功 请查看下载列表 未出现下载数据 可等待在刷新下载列表！"
            })
        }
    } catch (error) {
        ElMessage({
            type: "error",
            message: "下载失败 请稍后再试！"
        })
    }
}

const handPage = (val: { pageNum: number; pageSize: number }) => {
    listSearch.pageNum = val.pageNum;
    listSearch.pageSize = val.pageSize;
    getData("search");
};
const AddEdit = async (type: string, row?: any) => {
    if (type === "add") {
        channelAddEditRef.value?.show(type)

    } else {
        const res = await channelDetailApiGet({ id: row.id })
        channelAddEditRef.value?.show(type, res.data)
    }
}

const getData = async (type: string) => {
    pageParams.loadIng = true
    try {
        if (type === 'reset') {
            onlyTableRef.value.initPagination()
            listSearch.condition.channelCode = null
            listSearch.condition.channelKey = null
            listSearch.condition.channelName = null
            listSearch.pageNum = 1
            listSearch.pageSize = 20
        }
        const res = await channelPageApiPost(listSearch)
        if (res.code == 20000) {
            // auditStatus
            pageParams.tableData = res.data.records && res.data.records.map((item: any) => {
                return {
                    ...item,
                    auditStatus: auditStatus[item.auditStatus]
                }
            })
            pageParams.total = res.data.total
        }
    } catch (error) {
        console.log("渠道列表==》channelPageApiPost");

    } finally {
        pageParams.loadIng = false
        mittBus.emit('scrollUpdate')
    }
}

const delBtn = async (row: any) => {
    const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.channelName}`)
    if (flag) {
        const res = await channelDeleteApiDelete({ id: row.id })
        console.log(res.data);
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "数据删除成功"
            })
            getData('search')
        } else {
            ElMessage({
                type: "error",
                message: "数据删除失败"
            })
        }

    }

}
</script>


<style lang='scss' scoped>
.container-column {
    height: calc(100vh - 70px);

    .card-com {
        display: flex;
        flex-direction: column;
        // height: 100%;

        .card-2 {
            flex-grow: 1;
        }
    }
}
</style>
